package com.troll.wanandroid.view;

import android.content.Context;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.troll.wanandroid.R;

import rxhttp.wrapper.param.IFile;

/**
 * @Author: TangPeng
 * @Time: 5/13/21
 * @Remark:
 */
public class RefreshableView extends LinearLayout implements View.OnTouchListener {

    /**
     * 下拉的状态
     */
    public static final int STATUS_PULL_TO_REFRESH = 0;

    /**
     * 释放立即刷新状态
     */
    public static final int STATUS_RELEASE_TO_REFRESH = 1;

    /**
     * 刷新状态
     */
    public static final int STATUS_REFRESHING = 2;

    /**
     * 刷新完成或未刷新状态
     */
    public static final int STATUS_REFRESH_FINISHED = 3;


    /**
     * 下来头部回滚问题
     */
    public static final int SCROLL_SPEED = -20;


    private View header;
    private ProgressBar progressBar;
    private TextView description;
    private TextView updateAt;
    /**
     * 在判定定位滚动之前用户手指可以移动的最大的值
     */
    private int touchSlop;

    /**
     * 是否已经加载过一次layout
     */
    private boolean loadOnce;

    /**
     * 下拉头的高度
     */
    private int hideHeaderHeight;


    /**
     * 当前是否可以下拉，只有ListView滚动到头的时候才允许下拉
     */
    private boolean ableToPull;

    /**
     * 手指按下时屏幕纵坐标
     */
    private float yDown;

    private int currentStatus;
    private int lastStatus;

    private MarginLayoutParams headerLayoutParams;
    private ListView listView;
    private PullToRefreshListener mListener;

    public RefreshableView(Context context) {
        super(context);
        initView(context);
    }

    public RefreshableView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);

    }

    public RefreshableView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    public RefreshableView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView(context);
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        setIsAbleToPull(event);
        if (ableToPull) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    yDown = event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    float yMove = event.getRawY();
                    int distance = (int) (yMove - yDown);

                    // 手指是下滑状态，并且下拉头是隐藏的，屏蔽下拉事件
                    if (distance <= 0 && headerLayoutParams.topMargin <= hideHeaderHeight) {
                        return false;
                    }

                    if (distance < touchSlop) {
                        return false;
                    }
                    if (currentStatus != STATUS_REFRESHING) {
                        if (headerLayoutParams.topMargin > 0) {
                            currentStatus = STATUS_RELEASE_TO_REFRESH;
                        } else {
                            currentStatus = STATUS_PULL_TO_REFRESH;
                        }
                    }
                    // 通过偏移下拉头的TopMargin值，实现下拉效果
                    headerLayoutParams.topMargin = (distance / 2) + hideHeaderHeight;
                    header.setLayoutParams(headerLayoutParams);
                    break;
                case MotionEvent.ACTION_UP:
                default:
                    if (currentStatus == STATUS_RELEASE_TO_REFRESH) {
                        new RefreshingTask().execute();
                    } else if (currentStatus == STATUS_PULL_TO_REFRESH) {
                        new HideHeaderTask().execute();
                    }
                    break;
            }

            if (currentStatus == STATUS_PULL_TO_REFRESH
                    || currentStatus == STATUS_RELEASE_TO_REFRESH) {
                updateHeaderView();
                // 当前处于下拉或释放状态，让
                listView.setPressed(false);
                listView.setFocusable(false);
                listView.setFocusableInTouchMode(false);
                lastStatus = currentStatus;
                // 当前处于下拉或者释放状态，通过返回true屏蔽掉ListView滚动事件
                return true;
            }
        }
        return false;
    }

    /**
     * 根据当前ListView的滚动状态来设置
     *
     * @param event
     */
    private void setIsAbleToPull(MotionEvent event) {
        View firstChild = listView.getChildAt(0);
        if (firstChild != null) {
            int firstVisiblePos = listView.getFirstVisiblePosition();
            if (firstVisiblePos == 0 && firstChild.getTop() == 0) {
                if (!ableToPull) {
                    yDown = event.getRawY();
                }
                // 如果首个元素的上边缘，距离父布局值为0，说明滚动到最顶部，允许下拉刷新
                ableToPull = true;
            } else {
                if (headerLayoutParams.topMargin != hideHeaderHeight) {
                    headerLayoutParams.topMargin = hideHeaderHeight;
                    header.setLayoutParams(headerLayoutParams);
                }
                ableToPull = false;
            }
        } else {
            // 如果ListView中没有元素也运行下拉刷新
            ableToPull = true;
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed && !loadOnce) {
            hideHeaderHeight = -header.getHeight();
            headerLayoutParams = (MarginLayoutParams) header.getLayoutParams();
            headerLayoutParams.topMargin = hideHeaderHeight;
            listView = (ListView) getChildAt(1);
            listView.setOnTouchListener(this);
            loadOnce = true;
        }
    }

    private void initView(Context context) {
        header = LayoutInflater.from(context).inflate(R.layout.pull_to_refresh, null, false);
        progressBar = header.findViewById(R.id.progress_bar);
        description = header.findViewById(R.id.description);
        updateAt = header.findViewById(R.id.updated_at);

        touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();

        refreshUpdatedAtValue();
        setOrientation(VERTICAL);
        addView(header, 0);
    }

    private void setPullToRefreshListener(PullToRefreshListener listener) {
        this.mListener = listener;
    }

    private void refreshUpdatedAtValue() {
        updateAt.setText("刷新中");
    }


    private void finishRefreshing() {
        currentStatus = STATUS_REFRESH_FINISHED;
        new HideHeaderTask().execute();
    }

    private void updateHeaderView() {
        if (lastStatus != currentStatus) {
            if (currentStatus == STATUS_PULL_TO_REFRESH) {
                description.setText(getResources().getString(R.string.pull_to_refresh));
                progressBar.setVisibility(View.GONE);
            } else if (currentStatus == STATUS_RELEASE_TO_REFRESH) {
                description.setText(getResources().getString(R.string.release_to_refresh));
                progressBar.setVisibility(View.GONE);
            } else if (currentStatus == STATUS_REFRESHING) {
                description.setText(getResources().getString(R.string.refreshing));
                progressBar.setVisibility(View.VISIBLE);
            }
            refreshUpdatedAtValue();
        }
    }

    class RefreshingTask extends AsyncTask<Void, Integer, Void> {

        @Override
        protected Void doInBackground(Void... voids) {
            int topMargin = headerLayoutParams.topMargin;
            while (true) {
                topMargin = topMargin + SCROLL_SPEED;
                if (topMargin <= 0) {
                    topMargin = 0;
                    break;
                }
                publishProgress(topMargin);
                sleep(10);
            }
            currentStatus = STATUS_REFRESHING;
            publishProgress(0);
            if (mListener != null) {
                mListener.onRefresh();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            updateHeaderView();
            headerLayoutParams.topMargin = values[0];
            header.setLayoutParams(headerLayoutParams);
        }
    }

    class HideHeaderTask extends AsyncTask<Void, Integer, Integer> {

        @Override
        protected Integer doInBackground(Void... voids) {
            int topMargin = headerLayoutParams.topMargin;
            while (true) {
                topMargin = topMargin + SCROLL_SPEED;
                if (topMargin < hideHeaderHeight) {
                    topMargin = hideHeaderHeight;
                    break;
                }
                publishProgress(topMargin);
                sleep(10);
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            if (values == null) {
                headerLayoutParams.topMargin = 0;
            } else {
                headerLayoutParams.topMargin = values[0];
            }
            header.setLayoutParams(headerLayoutParams);
        }

        @Override
        protected void onPostExecute(Integer integer) {
            if (integer == null) {
                headerLayoutParams.topMargin = 0;
                header.setLayoutParams(headerLayoutParams);
                currentStatus = STATUS_REFRESH_FINISHED;
            } else {
                headerLayoutParams.topMargin = integer;
                header.setLayoutParams(headerLayoutParams);
                currentStatus = STATUS_REFRESH_FINISHED;
            }

        }
    }


    private void sleep(int time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public interface PullToRefreshListener {
        void onRefresh();
    }
}
